import {
  RECEIVE_MENU,
  RESET_MENU,
  RECEIVE_TOKEN,
  RESET_TOKEN,
  CLOSE_TAG
} from './mutations-type'
import Cookies from 'js-cookie'

const state = {
  menu: [],
  currentMenu: null,
  isCollapse: false,
  tagList: [
    {
      path: '/',
      name: 'home',
      label: '首页',
      icon: 's-home',
    },
  ] // tag标签栏
}

const mutations = {
  // 左侧菜单列表
  selectMenu (state, val) {
    if (val.label !== '首页') {
      state.currentMenu = val
      // 先判断之前的有没有该标签再添加
      let index = state.tagList.findIndex((item) => item.label === val.label)
      index === -1 ? state.tagList.push(val) : ''
    } else {
      state.currentMenu = null
    }
  },

  // 首页面板是否折叠
  handelCollapse (state) {
    state.isCollapse = !state.isCollapse
  },

  // 登录
  [RECEIVE_MENU] (state, menu) {
    state.menu = menu
  },
  [RECEIVE_TOKEN] (state, token) {
    state.token = token
  },

  // 退出登录
  [RESET_MENU] (state) {
    state.menu = []
    // 修复初始页面不显示的tag的bug
    state.tagList.splice(1)
  },
  [RESET_TOKEN] (state) {
    state.token = []
  },

  // 关闭tag
  [CLOSE_TAG] (state, tag) {
    let result = state.tagList.findIndex(item => item.name === tag.name)
    state.tagList.splice(result, 1)
  },

  // 动态添加路由
  addMenu (state, router) {
    let addMenu = []
    // 查看是否有菜单列表
    if (!Cookies.get('menuList')) {
      return
    }
    // 1. 获取后台的数据
    let menu = JSON.parse(Cookies.get('menuList'))
    if (!menu) {
      return
    }
    state.menu = menu

    // 2. 动态添加
    addMenu = [{
      path: '/',
      component: () => import('@/views/Home.vue'),
      children: []
    }]
    // 3. 遍历查找
    menu.map(item => {
      if (item.children) {
        item.children = item.children.map(item => {
          item.component = () => import(`@/views/${item.url}`)
          return item
        })
        addMenu[0].children.push(...item.children)
      } else {
        item.component = () => import(`@/views/${item.url}`)
        addMenu[0].children.push(item)
      }
    })
    // 4. 添加404
    addMenu.push({ path: '*', redirect: '/404' })
    // 5. 添加子路由
    router.addRoutes(addMenu)
  }
}

const actions = {
  // 同步登录请求
  saveInfo ({ commit }, data) {
    // 从user中提取token
    const token = data.token
    Cookies.set("token_key", token)

    commit(RECEIVE_TOKEN, token)

    Cookies.set("menuList", JSON.stringify(data.menu))
    commit(RECEIVE_MENU, data.menu)
  },

  // 同步退出登录
  resetInfo ({ commit }) {
    commit(RESET_MENU)
    commit(RESET_TOKEN)
    Cookies.remove("token_key")
    Cookies.remove("menuList")
  },

  // 关闭标签
  closeTag ({ commit }, tag) {
    commit(CLOSE_TAG, tag)
  }
}

const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}